<?php
/**
 * ランキングバッチコントローラー
 *
 * @package  app
 * @extends  Controller
 */
class Controller_Batch_Crawler extends Controller_Manage {
	/**
	 * iTunes ヒットチャートを曲との紐付け
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_ituneshit() {
		$this->get_itunesrss(Config::get('itunes_url_rss300'));

		return Response::forge('OK', D_HTTP_UPDATE);
	}

	/**
	 * iTunes ランキング上位の曲情報を取得する
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_itunessong() {
		// 最も再生されている曲を取得
		$query = DB::select('artist','song_title');
		$query -> from('song');
		$query -> where('itunes_update_date','1970-01-01');
		$query -> order_by('count_play','DESC');
		$query -> limit(1);
		$result = $query -> execute() -> as_array();
		
		if( count($result) != 0 ) {
			$artist = $result[0]['artist'];
			$song_title = $result[0]['song_title'];
			
			// iTunesから引く
			$this->get_itunesapi($artist .' '. $song_title, 300);
			
			// 該当なしでも検索済みにする
			$query = DB::update('song');
			$query -> set(array('itunes_update_date' => DB::expr('NOW()')));
			$query -> where('artist',$artist);
			$query -> where('song_title',$song_title);
			$query -> execute();
		}
		
		return Response::forge('OK', D_HTTP_UPDATE);
	}

	/**
	 * リワードAPI巡回
	 *
	 * @access  public
	 * @return  Response
	 */
	public function action_rewardapi() {
		$update = date('Y-m-d H:i:00', time());

		//-----------------------------
		// AppDriver
		//-----------------------------
		$company = 'appdrv';
		
		// 最終更新日を取得
		$query = DB::select(DB::expr('MAX(update_date) AS dt'));
		$query -> from('reward_api');
		$query -> where('ad_company', 'appdrv');
		$result = $query -> execute() -> as_array();
		$sec = time() - (isset($result[0]['dt']) ? strtotime($result[0]['dt']) : 0);
		if($sec > Config::get('reward_apprdv_apiinterval') ) {
			echo 'appdrv/';
			// APIをコール
			$d = Config::get('reward_appdrv_mediaId') . ':' . Config::get('reward_appdrv_siteKey');
			$digest = hash('sha256', $d, false);
			$url = sprintf(Config::get('reward_apprdv_apiurl'), Config::get('reward_appdrv_siteId'), Config::get('reward_appdrv_mediaId'), $digest);
			try {
				$curl = Request::forge($url, 'curl');
				$result = $curl -> execute() -> response();
				$result = Format::forge($result, 'XML') -> to_array();
				$results = $result['body']['campaign'];
				
				// DBに保存
				foreach( $results as $result) {
					$ad_id = $result['id'];
					$this->reward_insert( $company, $ad_id, $update, $result);
				}
			
				// 削除
				if( count($results) > 0 ) {
					$this->reward_delete( $company, $update);
				}
			} catch (\Exception $e) {
				$this -> alert($e);
			}
		}
		
		//-----------------------------
		// smaad
		//-----------------------------
		$company = 'smaad';

		// 最終更新日を取得
		$query = DB::select(DB::expr('MAX(update_date) AS dt'));
		$query -> from('reward_api');
		$query -> where('ad_company', 'smaad');
		$result = $query -> execute() -> as_array();
		$sec = time() - (isset($result[0]['dt']) ? strtotime($result[0]['dt']) : 0);
		if($sec > Config::get('reward_smaad_apiinterval') ) {
			echo 'smaad/';
			// APIをコール
			$results = array();
			try {
				$limit = 20;
				for($page = 1; $page < 99; $page ++) {
					$start = ($page - 1) * $limit + 1;
					$url = sprintf(Config::get('reward_smaad_apiurl'), Config::get('reward_smaad_zoneId'), $start, $limit);
					$curl = Request::forge($url, 'curl');
					$result = $curl -> execute() -> response();
					$result = json_decode( $result, true);
			
					// リストに積む
					for($i = 0; $i < $result['Result']['returned']; $i ++ ) {
						$results[] = $result['Result']['Items']['Item'][$i];
					}
			
					// 全件取得した
					if( $result['Result']['total'] <= $start + $result['Result']['returned']) {
						break;
					}
				}
				// DBに保存
				foreach( $results as $result) {
					$ad_id = $result['AdId'];
					$this->reward_insert( $company, $ad_id, $update, $result);
				}
			
				// 削除
				if( count($results) > 0 ) {
					$this->reward_delete( $company, $update);
				}
			} catch (\Exception $e) {
				$this -> alert($e);
			}
		}
		
		//-----------------------------
		// caリワード
		//-----------------------------
		$company = 'ca';

		// 最終更新日を取得
		$query = DB::select(DB::expr('MAX(update_date) AS dt'));
		$query -> from('reward_api');
		$query -> where('ad_company', 'ca');
		$result = $query -> execute() -> as_array();
		$sec = time() - (isset($result[0]['dt']) ? strtotime($result[0]['dt']) : 0);
		if($sec > Config::get('reward_ca_apiinterval') ) {
			echo 'ca/';
			// APIをコール
			$results = array();
			try {
				$limit = 30;
				for($page = 1; $page < 10; $page ++) {
					$start = ($page - 1) * $limit + 1;
					$url = sprintf(Config::get('reward_ca_apiurl'), Config::get('reward_ca_apikey'), Config::get('reward_ca_mid'), $page, $limit);
					$curl = Request::forge($url, 'curl');
					$result = $curl -> execute() -> response();
					$xml = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
					$result = json_decode(json_encode($xml), true);
						
					// リストに積む
					for($i = 0; $i < $result['total_cnt']; $i ++ ) {
						$results[] = $result['list_view']['ad'][$i];
					}
						
					// 全件取得した
					if( $result['data_cnt'] <= $start + $result['total_cnt']) {
						break;
					}
				}
				// DBに保存
				foreach( $results as $result) {
					$ad_id = $result['c_id'];
					$this->reward_insert( $company, $ad_id, $update, $result);
				}
			
				// 削除
				if( count($results) > 0 ) {
					$this->reward_delete( $company, $update);
				}
			} catch (\Exception $e) {
				$this -> alert($e);
			}
		}

		//-----------------------------
		// affilead
		//-----------------------------
		$company = 'affile';
		
		// 最終更新日を取得
		$query = DB::select(DB::expr('MAX(update_date) AS dt'));
		$query -> from('reward_api');
		$query -> where('ad_company', 'affile');
		$result = $query -> execute() -> as_array();
		$sec = time() - (isset($result[0]['dt']) ? strtotime($result[0]['dt']) : 0);
		if($sec > Config::get('reward_affilead_apiinterval') ) {
			echo 'affile/';
			// APIをコール
			require_once ("XML/RPC.php");
			$c = new XML_RPC_client(Config::get('reward_affilead_apipath'), Config::get('reward_affilead_apidomain'));
			$params = array(new XML_RPC_Value( array("site_no" => new XML_RPC_Value(Config::get('reward_affilead_siteNo'), "int"), "official" => new XML_RPC_Value(0, "int"), "kickback" => new XML_RPC_Value(1, "int")), "struct"));
			$message = new XML_RPC_Message('getAdData', $params);
			$res = $c -> send($message);
			if (!$res -> faultCode()) {
				$results = XML_RPC_decode($res -> value());

				// DBに保存
				foreach( $results as $result) {
					$ad_id = $result['ad_no'];
					$this->reward_insert( $company, $ad_id, $update, $result);
				}
				
				// 削除
				if( count($results) > 0 ) {
					$this->reward_delete( $company, $update);
				}
			}
			
		}
		
		//---------------------------
		// 自動追加
		//---------------------------
		$push = array();
		$list = $this->reward_api2view();
		foreach( $list as $l ) {
			// 対象判別
			if( $l['score'] < 1000) {
				continue;
			}
			
			// viewで公開中か
			$query = DB::select('reward_id');
			$query->from('reward_view');
			$query -> where('ad_company', $l['ad_company']);
			$query -> where('ad_id', $l['ad_id']);
			$query -> where('del', 0);
			$result = $query -> execute() -> as_array();
			if( count($result) > 0 ) {
				continue;
			}
			
			// 追加
			try {
				$query = DB::insert('reward_view');
				$query -> set($l);
				$query -> execute();
			} catch (\Exception $e) {
				$l['del'] = 0;
				$query = DB::update('reward_view');
				$query -> set( $l );
				$query -> where('ad_company', $l['ad_company']);
				$query -> where('ad_id', $l['ad_id']);
				$query -> execute();
			}
			
			$push[] = $l;
		}

		// push通知
		$text = '';
		if( count($push) == 1 ) {
			// 1件のみのとき
			$t = array(
				'新着★無料アプリ『%s』ポイントGETのチャンス♪',
				'無料アプリ追加♪『%s』',
				'無料アプリ『%s』でポイントGET',
				);
			$text = sprintf($t[ mt_rand(0,count($t)-1)], $push[0]['title']);
		} else if( count($push) == 2 ) {
			// 2件のとき
			$t = array(
				'無料アプリ追加★『%s』『%s』',
				'無料アプリ『%s』『%s』を追加！',
				);
			$text = sprintf($t[ mt_rand(0,count($t)-1)], $push[0]['title'],  $push[1]['title']);
		} else if( count($push) >= 3 ) {
			// 大量追加
			$t = array(
				'無料アプリ大量追加★『%s』など %d 本！',
				'無料アプリ一気に『%s』など %d 本追加♪',
				);
			$text = sprintf($t[ mt_rand(0,count($t)-1)], $push[0]['title'], count($push));
		}

		if( $text ) {
			$query = DB::Insert('push_bulk');
			$query -> set(array(
				'push_text' => $text,
			));
			$query -> execute();
		}
				
		
		return Response::forge('OK', D_HTTP_UPDATE);
	}

	/**
	 * リワードAPI履歴保存
	 *
	 * @access  public
	 * @return  Response
	 */
	public function reward_insert($company, $ad_id, $update, $data) {
		// api履歴に保存
		try {
			// 追加してみる
			$query = DB::insert('reward_api');
			$query -> set(array(
				'ad_company' => $company,
				'ad_id' => $ad_id,
				'update_date' => $update,
				'post_date' => $update,
				'data' => json_encode($data),
			));
			$query -> execute();
		} catch (\Exception $e) {
			// 情報更新
			$query = DB::update('reward_api');
			$query -> set(array(
				'data' => json_encode($data),
				'update_date' => $update,
			));
			$query -> where('ad_company', $company);
			$query -> where('ad_id', $ad_id);
			$query -> execute();

			// 削除済みだったら再開扱い
			$query = DB::update('reward_api');
			$query -> set(array(
				'del' => 0,
				'post_date' => $update,
			));
			$query -> where('ad_company', $company);
			$query -> where('ad_id', $ad_id);
			$query -> where('del', 1);
			$query -> execute();
		}
	}

	/**
	 * リワードAPI落ちた案件削除
	 *
	 * @access  public
	 * @return  Response
	 */
	public function reward_delete($company, $update) {
		$query = DB::update('reward_api');
		$query -> set(array(
			'del' => 1,
		));
		$query -> where('ad_company', $company);
		$query -> where('update_date', '<', $update);
		$query -> execute();
		
		// 表示要案件との突き合わせ
		$sql = "UPDATE reward_view SET del = 1 WHERE ad_company='%s' AND ad_id IN ";
		$sql .= "(SELECT ad_id FROM reward_api WHERE del=1 AND ad_company='%s')";
		$sql = sprintf($sql, $company, $company);
		DB::query($sql) -> execute();
				
	}

}
